import torch

x_data = torch.Tensor([[1.0], [2.0], [3.0]])  # 输入数据，这里是一个简单的1维特征，3个样本
y_data = torch.Tensor([[0], [0], [1]])  # 标签数据，0和1代表两个类别

class LogisticRegressionModel(torch.nn.Module):
    def __init__(self):
        super(LogisticRegressionModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        y_pred = torch.sigmoid(self.linear(x))
        return y_pred

model = LogisticRegressionModel()


criterion = torch.nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)

# 训练循环, 前向传播, 反向传播, 参数更新
for epoch in range(100):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data.float())
    print(epoch, loss.item())

    optimizer.zero_grad() # 清零梯度
    loss.backward()
    optimizer.step()

# 打印训练后的参数模型
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)

print('y_pred = ', y_test.data)
